package com.ruoyi.prod.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.prod.es.EsProd;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import com.ruoyi.prod.mapper.TbProdMapper;
import com.ruoyi.prod.domain.TbProd;
import com.ruoyi.prod.service.ITbProdService;

/**
 * 商品Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-09
 */
@Service
public class TbProdServiceImpl implements ITbProdService 
{
    @Autowired
    private TbProdMapper tbProdMapper;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 查询商品
     * 
     * @param prodId 商品主键
     * @return 商品
     */
    @Override
    public TbProd selectTbProdByProdId(Long prodId)
    {
        return tbProdMapper.selectTbProdByProdId(prodId);
    }

    /**
     * 查询商品列表
     * 
     * @param tbProd 商品
     * @return 商品
     */
    @Override
    public List<TbProd> selectTbProdList(TbProd tbProd)
    {
        return tbProdMapper.selectTbProdList(tbProd);
    }

    /**
     * 新增商品
     * 
     * @param tbProd 商品
     * @return 结果
     */
    @Override
    public int insertTbProd(TbProd tbProd)
    {
        tbProd.setCreateTime(DateUtils.getNowDate());
        return tbProdMapper.insertTbProd(tbProd);
    }

    /**
     * 修改商品
     * 
     * @param tbProd 商品
     * @return 结果
     */
    @Override
    public int updateTbProd(TbProd tbProd)
    {
        tbProd.setUpdateTime(DateUtils.getNowDate());
        return tbProdMapper.updateTbProd(tbProd);
    }

    /**
     * 批量删除商品
     * 
     * @param prodIds 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdIds(Long[] prodIds)
    {
        return tbProdMapper.deleteTbProdByProdIds(prodIds);
    }

    /**
     * 删除商品信息
     * 
     * @param prodId 商品主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdId(Long prodId)
    {
        return tbProdMapper.deleteTbProdByProdId(prodId);
    }

    @Override
    public AjaxResult createProdIndex() {
        //获取索引
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if (exists){
            indexOps.delete();
        }

        //创建索引
        indexOps.create();

        //创建映射
        Document mapping = indexOps.createMapping();
        //添加映射
        indexOps.putMapping(mapping);

        return AjaxResult.success("索引创建成功");
    }

    @Override
    public AjaxResult syncProdIndex() {
        List<TbProd> tbProds = tbProdMapper.selectTbProdList(new TbProd());
        for (TbProd tbProd : tbProds) {
            EsProd esProd = BeanUtil.toBean(tbProd, EsProd.class);
            elasticsearchRestTemplate.save(esProd);
        }

        return AjaxResult.success("数据同步成功");
    }

    @Override
    public TableDataInfo getListProdEs(TbProd tbProd, Integer pageNum, Integer pageSize) {
        //构造分页参数
        Integer from = 0;
        if (pageNum > 0){
            from = (pageNum - 1);
        }
        PageRequest pageRequest = PageRequest.of(from, pageSize);

        //构造查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
//        boolQueryBuilder.must(QueryBuilders.matchAllQuery());

        //商品名称分词查询
        if (StringUtils.isNotEmpty(tbProd.getProdName())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("prodName",tbProd.getProdName()));
        }

        //集成高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("prodName").postTags("<font color='red'>").postTags("</font>");

        //排序
        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("prodId").order(SortOrder.DESC);

        //开始ES查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withPageable(pageRequest)
                .withQuery(boolQueryBuilder)
                .withHighlightBuilder(highlightBuilder)
                .withSort(sortBuilder);

        SearchHits<EsProd> searchHits = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsProd.class);


        ArrayList<EsProd> list = new ArrayList<>();

        for (SearchHit<EsProd> searchHit : searchHits.getSearchHits()) {
            EsProd esProd = searchHit.getContent();

            //获取高亮字段
            List<String> prodNameList = searchHit.getHighlightField("ProdName");
            if (prodNameList != null && prodNameList.size() > 0){
                esProd.setProdName(prodNameList.get(0));
            }

            //添加到集合中
            list.add(esProd);
        }

        //返回分页数据
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
}
